package fm.dongman.modellib.source;

import android.support.annotation.NonNull;

import fm.dongman.animefm.contractlib.BaseDataSource;
import fm.dongman.animefm.contractlib.contract.SearchContract;
import fm.dongman.animefm.contractlib.model.SearchDataModel;
import fm.dongman.modellib.local.SearchLocalDataSource;
import fm.dongman.modellib.remote.SearchRemoteDataSource;

/**
 * Created by KUIGE on 2017/10/26.
 */

public class SearchRepository implements SearchContract.ISearchDataSource {

    private static SearchRepository SINGLETON;

    private SearchRemoteDataSource mRemote;
    private SearchLocalDataSource mLocal;

    private SearchDataModel models;


    private SearchRepository(SearchRemoteDataSource instance, SearchLocalDataSource searchLocalDataSource) {
        mRemote = instance;
        mLocal = searchLocalDataSource;
        mLocal.getData(new LoadSourceCallback<SearchDataModel>() {
            @Override
            public void onDataLoaded(SearchDataModel dataModel) {
                models = dataModel;
            }

            @Override
            public void onDataLoadFiled() {

            }
        });
    }

    public static SearchRepository getInstance(SearchRemoteDataSource instance, SearchLocalDataSource searchLocalDataSource) {
        if (SINGLETON == null) {
            SINGLETON = new SearchRepository(instance, searchLocalDataSource);
        }
        return SINGLETON;
    }

    @Override
    public void getData(@NonNull final BaseDataSource.LoadSourceCallback<? super SearchDataModel> callback) {
        mRemote.getData(new LoadSourceCallback<SearchDataModel>() {
            @Override
            public void onDataLoaded(SearchDataModel dataModel) {
                SearchDataModel model = new SearchDataModel();
                if (dataModel.getHotSearchList().size() != 0) {
                    model.setHotSearchList(dataModel.getHotSearchList());
                    model.setHistorySearchList(dataModel.getHistorySearchList());
                    callback.onDataLoaded(model);
                } else {
                    callback.onDataLoaded(models);
                }

            }

            @Override
            public void onDataLoadFiled() {
                if (models.getHotSearchList().size() > 0 | models.getHistorySearchList().size() > 0) {
                    callback.onDataLoaded(models);
                } else {
                    callback.onDataLoadFiled();
                }
            }
        });
    }

    @Override
    public void saveData(SearchDataModel dataModel) {
    }

    @Override
    public void refreshData() {

    }

    @Override
    public void offLine() {
        mRemote.offLine();
    }

    @Override
    public void clearHistorySearch(LoadSourceCallback<? super String> loadSourceCallback) {
        mLocal.clearHistorySearch(loadSourceCallback);
    }
}
